import { defineStore } from 'pinia';
import type { NotificationItem } from '@/types/interface';
import { onWebSocket, onSse } from '@/soar';

export const useNotificationStore = defineStore('notification', {
  state: () => ({
    total: 0 as number,
    list: [] as NotificationItem[],
  }),
  actions: {
    update(total: number, list: NotificationItem[]) {
      this.total = total;
      this.list = list;
    },
    incr(item: NotificationItem) {
      this.total++;
      if (this.list.length < 10) {
        this.list.push(item);
      }
    },
  },
  persist: false,
});
// 监听 WebSocket 消息
onWebSocket('notice', (data) => {
  data = JSON.parse(data);
  useNotificationStore().update(data.total, data.list);
});
onSse('notice', (data) => {
  data = JSON.parse(data);
  useNotificationStore().update(data.total, data.list);
});
// 监听 WebSocket 消息
onWebSocket('notice-incr', (data) => {
  useNotificationStore().incr(JSON.parse(data));
});
onSse('notice-incr', (data) => {
  useNotificationStore().incr(JSON.parse(data));
});
